<?php
// 启动会话
session_start();

// 检查是否已登录
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: index.php');
    exit;
}

// 检查是否提供了工单ID
if (!isset($_GET['id']) || empty($_GET['id'])) {
    header('Location: admin_dashboard.php');
    exit;
}

$ticketId = $_GET['id'];
$success_message = '';
$error_message = '';

// 引入数据库配置
require '../config.php';
// 引入发送邮件函数
require '../send_email.php';

// 处理邮件回复表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reply_email'])) {
    $subject = $_POST['subject'];
    $message = $_POST['message'];
    
    if (empty($subject) || empty($message)) {
        $error_message = '主题和内容不能为空';
    } else {
        // 获取工单详情以获取QQ号码
        try {
            $sql = "SELECT qq_number FROM tickets WHERE id = :id";
            $stmt = $pdo->prepare($sql);
            $stmt->bindParam(':id', $ticketId, PDO::PARAM_INT);
            $stmt->execute();
            $ticket = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($ticket) {
                $qq_number = $ticket['qq_number'];
                
                // 处理文件上传
                $attachments = [];
                if (!empty($_FILES['attachments']['name'][0])) {
                    $upload_dir = '../uploads/';
                    // 确保上传目录存在
                    if (!file_exists($upload_dir)) {
                        mkdir($upload_dir, 0777, true);
                    }
                    
                    foreach ($_FILES['attachments']['tmp_name'] as $key => $tmp_name) {
                        $file_name = $_FILES['attachments']['name'][$key];
                        $file_size = $_FILES['attachments']['size'][$key];
                        $file_tmp = $_FILES['attachments']['tmp_name'][$key];
                        $file_type = $_FILES['attachments']['type'][$key];
                        
                        // 只允许图片文件
                        if (strpos($file_type, 'image/') === 0) {
                            $target_path = $upload_dir . time() . '_' . basename($file_name);
                            if (move_uploaded_file($file_tmp, $target_path)) {
                                $attachments[] = $target_path;
                            }
                        }
                    }
                }
                
                // 发送邮件
                $success = send_email_by_qq($qq_number, $subject, $message, $attachments);
                if ($success) {
                    $success_message = '邮件回复成功！';
                    // 清空表单
                    $_POST['subject'] = '';
                    $_POST['message'] = '';
                } else {
                    $error_message = '邮件发送失败，请检查SMTP设置';
                }
            } else {
                $error_message = '未找到该工单';
            }
        } catch(PDOException $e) {
            $error_message = '数据库错误: ' . $e->getMessage();
        }
    }
}

// 获取工单详情
try {
    $sql = "SELECT * FROM tickets WHERE id = :id";
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':id', $ticketId, PDO::PARAM_INT);
    $stmt->execute();
    $ticket = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$ticket) {
        $error = '未找到该工单';
    }
} catch(PDOException $e) {
    $error = '数据库错误: ' . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>✿ 工单详情 - <?php echo $ticketId; ?> ✿</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=ZCOOL+KuaiLe&family=Ma+Shan+Zheng&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="styles_anime_admin.css">
    <script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/gsap@3.11.3/dist/gsap.min.js"></script>
    <style>
        .ticket-detail-container {
            max-width: 800px;
            margin: 30px auto;
            padding: 25px;
            background-color: var(--surface);
            border-radius: 24px;
            box-shadow: 0 10px 30px rgba(255, 107, 139, 0.2);
            position: relative;
            overflow: hidden;
            border: 3px solid var(--border);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        .header h1 {
            margin: 0;
            position: relative;
        }
        .header h1::before,
        .header h1::after {
            content: '✿';
            color: var(--secondary);
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            font-size: 1.5rem;
        }
        .header h1::before {
            left: -30px;
        }
        .header h1::after {
            right: -30px;
        }
        .back-btn {
            padding: 10px 20px;
            background-color: var(--secondary);
            color: white;
            border: none;
            border-radius: 50px;
            cursor: pointer;
            text-decoration: none;
            font-size: 1rem;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            box-shadow: 0 4px 8px rgba(138, 92, 242, 0.3);
        }
        .back-btn:hover {
            background-color: var(--secondary-light);
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(138, 92, 242, 0.4);
        }
        .ticket-info {
            background-color: rgba(255, 255, 255, 0.7);
            border-radius: 16px;
            box-shadow: 0 5px 15px rgba(255, 107, 139, 0.1);
            padding: 20px;
            margin-bottom: 25px;
            border: 2px solid var(--border);
        }
        .info-row {
            margin-bottom: 15px;
        }
        .info-label {
            font-weight: bold;
            color: var(--primary);
            margin-bottom: 8px;
            font-size: 1.1rem;
        }
        .info-value {
            word-break: break-word;
        }
        .screenshot-container {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-top: 10px;
        }
        .screenshot-item {
            max-width: 200px;
            border: 1px solid #ddd;
            border-radius: 4px;
            overflow: hidden;
        }
        .screenshot-item img {
            width: 100%;
            height: auto;
            display: block;
        }
        .no-screenshots {
            color: #777;
            font-style: italic;
        }
        .reply-container {
            background-color: rgba(255, 255, 255, 0.7);
            border-radius: 16px;
            box-shadow: 0 5px 15px rgba(255, 107, 139, 0.1);
            padding: 20px;
            margin-top: 30px;
            border: 2px solid var(--border);
        }
        .reply-form {
            margin-top: 15px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
        }
        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .form-group textarea {
            height: 150px;
            resize: vertical;
        }
        .btn-reply {
            padding: 10px 20px;
            background-color: var(--primary);
            color: white;
            border: none;
            border-radius: 50px;
            cursor: pointer;
            font-size: 1rem;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            box-shadow: 0 4px 8px rgba(255, 107, 139, 0.3);
        }
        .btn-reply:hover {
            background-color: var(--primary-light);
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(255, 107, 139, 0.4);
        }
        .success-message {
            background-color: #2ecc71;
            color: white;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 20px;
            text-align: center;
        }
        .error-message {
            background-color: #e74c3c;
            color: white;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 20px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="ticket-detail-container">
        <div class="header">
            <div class="anime-decoration"></div>
            <h1>工单详情 #<?php echo $ticketId; ?></h1>
            <a href="admin_dashboard.php" class="back-btn">
                <span>返回列表</span>
                <span class="heart">♡</span>
            </a>
        </div>

        <?php if (isset($error)): ?>
            <div class="error-message"><?php echo $error; ?></div>
        <?php elseif ($ticket): ?>
            <div class="ticket-info">
                <div class="info-row">
                    <div class="info-label">QQ号码</div>
                    <div class="info-value"><?php echo $ticket['qq_number']; ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">反馈类型</div>
                    <div class="info-value"><?php 
                        $typeMap = [
                            'account' => '账号问题',
                            'function' => '功能故障',
                            'suggestion' => '功能建议',
                            'performance' => '性能问题',
                            'security' => '安全问题',
                            'other' => '其他问题'
                        ];
                        echo $typeMap[$ticket['feedback_type']] ?? $ticket['feedback_type'];
                    ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">问题严重程度</div>
                    <div class="info-value"><?php 
                        $stars = '';
                        for ($i = 1; $i <= 5; $i++) {
                            if ($i <= $ticket['severity']) {
                                $stars .= '★';
                            } else {
                                $stars .= '☆';
                            }
                        }
                        echo $stars;
                    ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">提交时间</div>
                    <div class="info-value"><?php echo date('Y-m-d H:i:s', strtotime($ticket['created_at'])); ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">问题描述</div>
                    <div class="info-value"><?php echo nl2br(htmlspecialchars($ticket['description'])); ?></div>
                </div>
                <div class="info-row">
                    <div class="info-label">上传截图</div>
                    <div class="info-value">
                        <?php if (!empty($ticket['screenshots'])): ?>
                            <div class="screenshot-container">
                                <?php 
                                    $screenshots = explode(',', $ticket['screenshots']);
                                    foreach ($screenshots as $screenshot):
                                ?>
                                    <div class="screenshot-item">
                                        <img src="<?php echo '../' . $screenshot; ?>" alt="截图">
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                            <div class="no-screenshots">无截图</div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php endif; ?>
        <?php if ($ticket): ?>
            <div class="reply-container">
                <h2>邮件回复</h2>
                <p>回复工单 #<?php echo $ticketId; ?> 的提交者 (QQ: <?php echo $ticket['qq_number']; ?>)</p>
                
                <?php if (!empty($success_message)): ?>
                    <div class="success-message"><?php echo $success_message; ?></div>
                <?php endif; ?>
                
                <?php if (!empty($error_message)): ?>
                    <div class="error-message"><?php echo $error_message; ?></div>
                <?php endif; ?>
                
                <form class="reply-form" method="POST" action="view_ticket.php?id=<?php echo $ticketId; ?>" enctype="multipart/form-data">
                    <input type="hidden" name="reply_email" value="1">
                    <div class="form-group">
                        <label for="subject">邮件主题</label>
                        <input type="text" id="subject" name="subject" value="<?php echo isset($_POST['subject']) ? htmlspecialchars($_POST['subject']) : '关于您的工单 #' . $ticketId . ' 的回复'; ?>" required>
                    </div>
                    <div class="form-group">
                        <label for="message">邮件内容</label>
                        <textarea id="message" name="message" required><?php echo isset($_POST['message']) ? htmlspecialchars($_POST['message']) : ''; ?></textarea>
                    </div>
                    <div class="form-group">
                        <label for="attachments">添加图片附件 (可多选)</label>
                        <input type="file" id="attachments" name="attachments[]" multiple accept="image/*">
                        <small>支持JPG、PNG、GIF等图片格式</small>
                    </div>
                    <button type="submit" class="btn-reply">
                <span>发送回复</span>
                <span class="heart">♡</span>
            </button>
                </form>
            </div>
        <?php endif;
    ?></div>
<script src="script_anime_admin.js"></script>
</body>
</html>